package com.gxz.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.util.Properties;

public class MybatisConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setTypeAliasesPackage("com.gxz.pojo");


        // 数据库驼峰转换的方法
        Configuration config = new Configuration();
        config.setMapUnderscoreToCamelCase(true);


        // 添加PageHelper分页插件配置
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        properties.setProperty("reasonable", "true");
        pageInterceptor.setProperties(properties);
        config.addInterceptor(pageInterceptor);

        sqlSessionFactory.setConfiguration(config);


        // 设置Mapper XML位置
//        PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
//        Resource resource = patternResolver.getResource("classpath:mybatis-config.xml");
//        sqlSessionFactory.setMapperLocations(resource);


        return sqlSessionFactory;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.gxz.mapper");
        return msc;
    }
}
